package com.visec.hdy.hadoop.context;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.visec.hdy.hadoop.standard.ReadContext;

/**
 * 文件读取上下文
 * 
 * @author hdy
 *
 */
public class FileReadContextImpl extends DefaultContextImpl implements ReadContext {
	protected List<File> files;
	protected File file;

	public FileReadContextImpl(String nameSpace, long count) {
		super(nameSpace, count);
	}

	@Override
	public long read(long l) {
		if (current == this.files.size())
			return -1;
		this.file = this.files.get((int) current);
		current++;
		return 1;
	}

	@Override
	public void seek(long l) {
		this.current = 0;
		skip(l);
	}

	@Override
	public void setQueryFile(List<File> files) {
		seek(0);
		this.files = sortFiles(files);
	}

	@Override
	public File getFile() {
		return this.file;
	}

	@Override
	public void setEndCurrent(long l) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void setStartCurrent(long l) {
		throw new UnsupportedOperationException();
	}

	@Override
	public long dataCount() {
		return this.files == null ? 0 : this.files.size();
	}

	@Override
	public List<File> sortFiles(List<File> files) {
		this.files = new ArrayList<>();
		files.stream().sorted((a, b) -> a.isDirectory() && b.isFile() ? -1 : 1).forEach(this.files::add);
		return this.files;
	}
}
